<template>
  <div ref="accessControlRulesRef" class="access-control-rules-box">
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane :key="1" tab="住宿学生进出时间" />
      <a-tab-pane :key="2" tab="住宿教职工进出时间" />
    </a-tabs>
    <div v-show="activeKey === 1" class="access-control-main-box">
      <list-comp ref="studentRef" :access-control-rules-ref="accessControlRulesRef"></list-comp>
      <!-- :access-control-rules-ref="accessControlRulesRef" -->
    </div>
    <div v-show="activeKey === 2" class="access-control-main-box">
      <list-comp-teacher
        ref="teacherRef"
        :is-disabled="true"
        :access-control-rules-ref="accessControlRulesRef"
      ></list-comp-teacher>
    </div>
    <div class="access-control-btn-box">
      <div class="flex items-center justify-center" @click="cancle">取消</div>
      <a-button
        type="primary"
        class="flex items-center justify-center"
        :loading="btnLoading"
        @click="save"
        >保存</a-button
      >
    </div>
    <!--取消返回 提示框 -->
    <my-dialog
      :dialog-state="cancelLamp.visible"
      :dialog-title="cancelLamp.title"
      :dialog-width="cancelLamp.width"
      :show-cancel="true"
      :icon-type="cancelLamp.iconType"
      @handleCancel="cancelLamp.visible = false"
      @handleOk="onCancelLampLamp"
    >
      <template v-slot:location>
        <div class="checkOutStyle">
          <img src="@/assets/images/accommodation/drawable-xxxhdpi_popu_icon_warn.png" alt="" />
          <span>规则未保存，是否确认离开？</span>
        </div>
      </template>
    </my-dialog>
  </div>
</template>

<script setup>
import { ref, watch, defineEmits, computed, onMounted, defineExpose } from 'vue';
import { message } from 'ant-design-vue';
import { useStore } from 'vuex';
import { getRgba } from '@/utils/validate.js';
// const emits = defineEmits('skipIndex');
let emits = defineEmits(['cancelAccessControlRules', 'skipIndex']);
import MyDialog from '@/components/dialog/index.vue';
import ListComp from './list.vue';
import ListCompTeacher from './listTeacher.vue';
import { getTimeGroupList, saveTimeGroup, allowAdminAccess } from '@/api/ruleSetting';
import { debounce } from '@/utils/debounce.js';
// 查询宿舍时间组 0 是学生 1是教职工
// 保存时间组(添加和修改)
const store = useStore();
const studentRef = ref(null);
const teacherRef = ref(null);
const studentTimeList = ref([]);
const teacherTimeList = ref([]);
// tabs key
let activeKey = ref(1);
// accessControl
const accessControl = computed(() => {
  return store.state.user.accessControl;
});
const accessControlTwo = computed(() => {
  return store.state.user.accessControlTwo;
});
// const setDoorRule = computed(() => {
//   return store.state.user.doorRule;
// });
// watch(
//   setDoorRule,
//   (newVal, oldVal) => {
//     console.log('setDoorRule-oldVal', oldVal);
//     console.log('setDoorRule-newVal', newVal);
//     if (newVal * 1 === 1) {
//       if (activeKey.value * 1 === 1) {
//         studentRef.value.GetTimeGroupList(0);
//       } else {
//         teacherRef.value.GetTimeGroupList(1);
//       }
//     }
//   },
//   { immediate: true, deep: true }
// );
const accessControlRulesRef = ref(null);
setTimeout(() => {
  document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.width = '106px';
  document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.left = '11px';
}, 100);
watch(
  accessControl,
  (newVal, oldVal) => {
    console.log('accessControl-oldVal', oldVal);
    console.log('accessControl-newVal', newVal);
  },
  { immediate: true, deep: true }
);
watch(
  accessControlTwo,
  (newVal, oldVal) => {
    console.log('accessControlTwo-oldVal', oldVal);
    console.log('accessControlTwo-newVal', newVal);
  },
  { immediate: true, deep: true }
);
watch(
  () => activeKey.value,
  val => {
    if (val === 1) {
      setTimeout(() => {
        document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.width = '106px';
        document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.left = '11px';
      }, 100);
    } else {
      setTimeout(() => {
        document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.width = '122px';
        document.getElementsByClassName('micro-dormitory-tabs-ink-bar')[0].style.left = '171px';
      }, 100);
    }
  }
);
onMounted(() => {});

const cancle = () => {
  cancelLamp.value.visible = true;
};
function some(arr) {
  let some = [];
  arr.forEach(el => {
    if (el.id && el.id !== null && el.id !== undefined) {
      if (!some.some(e => e.id === el.id)) {
        some.push(el);
      }
    } else {
      some.push(el);
    }
  });
  return some;
}
function upData() {
  if (activeKey.value * 1 === 1) {
    studentRef.value.GetTimeGroupList(0);
    // studentRef.value.getSection();

    studentRef.value.GetTimePermission(0);
  } else {
    teacherRef.value.GetTimeGroupList(1);
  }
}
const btnLoading = ref(false);
const save = debounce(async () => {
  console.log('qnimd', studentRef.value.ruleList);

  let isErr = false;
  if (activeKey.value * 1 === 1) {
    // studentRef.value.validateFields();
    if (studentRef.value.gradeIdListHis.length === 0) {
      message.error(`暂无年级数据`);
      return false;
    }
    studentRef.value.ruleList.forEach((item, index) => {
      if (!item.ruleName.length || !item.time.length || !item.area.length) {
        item.isErr = true;
        isErr = true;
      }
      if (!item.ruleName) {
        message.error(`第${index + 1}条 规则名称 未填写`);
        return false;
      }
      console.log('gradeIdListHis-------------', studentRef.value.gradeIdListHis);
      // if (studentRef.value.gradeIdListHis.length !== 0) {
      if (item.gradeIdList.length === 0) {
        message.error(`第${index + 1}条 生效范围 未选择`);
        return false;
      }
      // }
      if (!item.ruleStartTime || !item.ruleStopTime) {
        message.error(`第${index + 1}条 时间规则 未选择`);
        return false;
      }
    });
  } else {
    // teacherRef.value.validateFields();
    teacherRef.value.ruleList.forEach((item, index) => {
      if (!item.ruleName.length || !item.time.length || !item.area.length) {
        item.isErr = true;
        isErr = true;
      }
      if (!item.ruleName) {
        message.error(`第${index + 1}条 规则名称 未填写`);
        return false;
      }
      if (!item.ruleStartTime || !item.ruleStopTime) {
        message.error(`第${index + 1}条 时间规则 未选择`);
        return false;
      }
    });
  }

  if (isErr) {
    // message.warning('必填选项不能为空');
    return;
  }

  // 保存时间组(添加和修改)
  let data = {};
  if (activeKey.value * 1 === 1) {
    let studentList = some(studentRef.value.ruleList);
    // let studentList = studentRef.value.ruleList;
    data = {
      ruleType: 0, // 0学生 1教职工
      deleteIds: studentRef.value.deleteArr || [], // 要删除的时间组id
      settingList: disposeData(studentList)
    };
    // return;
  } else {
    let teacherList = some(teacherRef.value.ruleList);
    data = {
      ruleType: 1, // 0学生 1教职工
      deleteIds: teacherRef.value.deleteArr || [], // 要删除的时间组id
      settingList: teacherList
    };
  }
  console.log('新增的data', data);

  btnLoading.value = true;
  saveTimeGroup(data)
    .then(res => {
      console.log('新增', res);
      if (res.data.code === 200) {
        if (activeKey.value * 1 === 1) {
          allowAdminAccess({
            allowAdmin: studentRef.value.adminChecked ? 1 : 0,
            id: studentRef.value.permissionData.id
          }).then(() => {});
        }
        if (activeKey.value * 1 === 1) {
          studentRef.value.GetTimeGroupList(0);
        } else {
          teacherRef.value.GetTimeGroupList(1);
        }
        emits('skipIndex');
        setTimeout(() => {
          if (activeKey.value * 1 === 1) {
            studentRef.value.cancelRed();
          } else {
            teacherRef.value.cancelRed();
          }
        }, 500);
        btnLoading.value = false;
        message.success('保存成功');
      }
    })
    .catch(() => {
      btnLoading.value = false;
    });
  // setTimeout(() => {
  //   emits('skipIndex');
  // }, 500);
}, 500);
function emptyAllDel() {
  if (activeKey.value * 1 === 1) {
    studentRef.value.emptyDel();
  } else {
    teacherRef.value.emptyDel();
  }
}
// 取消规则按钮
const cancelLamp = ref({
  title: '温馨提示',
  visible: false,
  width: '328px',
  iconType: 'default'
});
// 确认
const onCancelLampLamp = () => {
  console.log('wqwqwqwq');
  store.commit('user/setDoorRule', 0);
  // toRuleSetting(-1);
  // store.commit('user/setRuleStatus', -1);
  cancelLamp.value.visible = false;
  emits('skipIndex');
  // emits('cancelAccessControlRules', -1);
};
// 处理生效范围
const disposeData = data => {
  let nowData = JSON.parse(JSON.stringify(data));
  nowData.forEach(item => {
    let isAll = item.isAreaAll;
    console.log(isAll, 'isAll');
    if (isAll) {
      item.gradeIdList = studentRef.value.gradeIdList;
    } else {
      let gradeIdList = [];
      item.area.forEach(itemChild => {
        if (itemChild.length === 1) {
          let filterData = studentRef.value.sectionList.filter(
            itemSection => itemSection.value === itemChild[0]
          );
          console.log(filterData, 'filterData');
          filterData.length ? gradeIdList.push(...filterData[0].gradeIds) : '';
        } else if (itemChild.length === 2) {
          gradeIdList.push(itemChild[1]);
        }
      });
      item.gradeIdList = gradeIdList;
    }
  });
  console.log(nowData, 'data');
  return nowData;
};
defineExpose({
  upData,
  emptyAllDel
});
// 定义颜色变量
const setStyles = computed(() => {
  return {
    '--primaryColor': store.state.user.primaryColor,
    primaryColor: store.state.user.primaryColor,
    backgroundColor: getRgba(store.state.user.primaryColor, 0.1)
  };
});
</script>

<style lang="less" scoped>
@import './accessControlRules.less';
.access-control-btn-box {
  display: flex;
  justify-content: center;
  padding: 16px 0;
  > div,
  ::v-deep(.micro-dormitory-btn) {
    width: 116px;
    height: 36px;
    background: v-bind('setStyles.primaryColor');
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 400;
    color: #ffffff;
  }

  div:first-child {
    background: #ffffff;
    border: 1px solid #e1dddd;
    color: #999999;
    margin-right: 16px;
  }
  div:first-child:hover {
    border-color: v-bind('setStyles.primaryColor');
    color: v-bind('setStyles.primaryColor');
  }
  div:last-child:hover {
    opacity: 0.9;
  }
  div:last-child:active {
    opacity: 1;
  }
}
</style>
